<template>
  <view class="profile-page">
    <!-- 加载状态 -->
    <view class="loading-container" v-if="pageLoading">
      <view class="loading-spinner"></view>
      <text>加载中...</text>
    </view>

    <scroll-view v-else scroll-y="true" @scrolltolower="onReachBottom" class="profile-scroll">
      <view class="user-header">
        <view class="user-info">
          <image class="avatar" :src="userInfo.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
          <view class="info-content">
            <view class="username">{{ userInfo.nickname || userInfo.username || '未知用户' }}</view>
            <view class="bio">{{ userInfo.bio || '这个人很懒，什么都没写~' }}</view>
          </view>
        </view>
        
        <!-- 操作区域 -->
        <view class="action-area">
          <!-- 关注按钮 -->
          <view v-if="!isCurrentUser && userId">
            <follow-button 
              :user-id="userId" 
              @follow-change="onFollowChange"
            ></follow-button>
          </view>
          
          <!-- 编辑资料按钮 -->
          <view v-if="isCurrentUser" class="edit-profile-btn" @click="navigateToEditProfile">
            <text>编辑资料</text>
          </view>
        </view>
      </view>

      <!-- 用户统计 -->
      <view class="user-stats">
        <!-- <view class="stat-item" >
          <text class="count">{{ followersCount }}</text>
          <text class="label">粉丝</text>
        </view>
        <view class="stat-item" >
          <text class="count">{{ followingCount }}</text>
          <text class="label">关注</text>
        </view> -->
        <view class="stat-item">
          <text class="count">{{ worksCount }}</text>
          <text class="label">作品</text>
        </view>
      </view>

      <!-- 作品列表 -->
      <view class="works-section">
        <view class="section-title">作品</view>
        <view v-if="works.length === 0 && !loading" class="empty-works">
          <image src="/static/images/empty-works.png" mode="aspectFit" class="empty-image"></image>
          <text>{{ isCurrentUser ? '你还没有创作作品' : '该用户暂无作品' }}</text>
          <button v-if="isCurrentUser" class="create-btn" @click="navigateToCreate">开始创作</button>
        </view>
        <view v-else class="works-grid">
          <view 
            v-for="work in works" 
            :key="work.id" 
            class="work-item"
            @click="navigateToWork(work.id)"
          >
            <image :src="work.resultImage || work.previewUrl || '/static/images/default-image.png'" mode="aspectFill"></image>
            <view class="work-info">
              <text class="work-title">{{ work.title || '未命名作品' }}</text>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <view v-if="loading" class="loading">
          <view class="loading-spinner"></view>
          <text>加载中...</text>
        </view>
        <view v-if="!loading && !hasMore && works.length > 0" class="no-more">
          <text>没有更多作品了</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { userApi } from '@/utils/api.js';
import FollowButton from '@/components/user/FollowButton.vue';

export default {
  components: {
    FollowButton
  },
  data() {
    return {
      userId: null,
      userInfo: {},
      works: [],
      worksCount: 0,
      followersCount: 0,
      followingCount: 0,
      page: 1,
      size: 12,
      loading: false,
      pageLoading: true,
      hasMore: true,
      isCurrentUser: false,
      error: null
    };
  },
  onLoad(options) {
    console.log('用户详情页面接收到的参数：', options);
    if (!options.id) {
      this.handleError('用户ID不存在');
      return;
    }
    
    this.userId = options.id;
    this.initPage();
  },
  onPullDownRefresh() {
    this.refreshPage();
  },
  onReachBottom() {
    if (!this.loading && this.hasMore) {
      this.page++;
      this.loadUserWorks(true);
    }
  },
  methods: {
    // 初始化页面
    async initPage() {
      this.pageLoading = true;
      try {
        await Promise.all([
          this.loadUserInfo(),
          this.checkIsCurrentUser()
        ]);
        await this.loadUserWorks();
      } catch (error) {
        this.handleError('加载页面失败', error);
      } finally {
        this.pageLoading = false;
        uni.stopPullDownRefresh();
      }
    },
    
    // 刷新页面
    refreshPage() {
      this.page = 1;
      this.works = [];
      this.hasMore = true;
      this.initPage();
    },
    
    // 加载用户信息
    async loadUserInfo() {
      try {
        const res = await userApi.getUserInfoById(this.userId);
        if (res.code === 200 && res.data) {
          this.userInfo = res.data;
          // 加载统计数据
          await this.loadStats();
          return true;
        } else {
          throw new Error(res.message || '获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
        return false;
      }
    },
    
    // 加载统计数据
    async loadStats() {
      try {
        // 获取作品数量
        const worksRes = await userApi.getUserWorks({ userId: this.userId, page: 1, size: 1 });
        if (worksRes.code === 200) {
          this.worksCount = worksRes.data.total || 0;
        }
        
        // 获取粉丝数量
        const followersRes = await userApi.getFollowers(this.userId);
        if (followersRes.code === 200) {
          this.followersCount = followersRes.data.length || 0;
        }
        
        // 获取关注数量
        const followingRes = await userApi.getFollowing(this.userId);
        if (followingRes.code === 200) {
          this.followingCount = followingRes.data.length || 0;
        }
      } catch (error) {
        console.error('获取统计数据失败:', error);
      }
    },
    
    // 加载用户作品
    async loadUserWorks(loadMore = false) {
      if (this.loading) return;
      
      try {
        this.loading = true;
        
        const res = await userApi.getUserWorks({
          userId: this.userId,
          page: this.page,
          size: this.size
        });
        
        if (res.code === 200 && res.data) {
          const { list, total } = res.data;
          console.log('获取用户作品:', list, total);
          
          if (loadMore) {
            this.works = [...this.works, ...list];
          } else {
            this.works = list;
          }
          console.log('加载更多:', this.works);
          
          this.hasMore = this.works.length < total;
          return true;
        } else {
          throw new Error(res.message || '获取用户作品失败');
        }
      } catch (error) {
        console.error('获取用户作品失败:', error);
        if (!loadMore) {
          uni.showToast({
            title: '获取作品失败',
            icon: 'none'
          });
        }
        return false;
      } finally {
        this.loading = false;
      }
    },
    
    // 检查是否为当前用户
    async checkIsCurrentUser() {
      try {
        const currentUser = await userApi.getCurrentUser();
        if (currentUser.code === 200 && currentUser.data) {
          this.isCurrentUser = currentUser.data.id == this.userId; // 使用 == 而不是 === 以处理字符串和数字的比较
          console.log('当前用户检查:', currentUser.data.id, this.userId, this.isCurrentUser);
          return true;
        }
        return false;
      } catch (error) {
        console.error('检查用户身份失败:', error);
        return false;
      }
    },
    
    // 关注状态变化处理
    onFollowChange(isFollowing) {
      // 更新粉丝数量
      this.followersCount += isFollowing ? 1 : -1;
      if (this.followersCount < 0) this.followersCount = 0;
    },
    
    // 导航到作品详情
    navigateToWork(workId) {
      if (!workId) {
        console.warn('作品ID不存在，无法跳转');
        return;
      }
      
      uni.navigateTo({
        url: `/pages/detail/detail?id=${workId}`
      });
    },
    
    // 导航到粉丝列表
    navigateToFollowers() {
      if (this.followersCount <= 0) {
        uni.showToast({
          title: '暂无粉丝',
          icon: 'none'
        });
        return;
      }
      
      uni.navigateTo({
        url: `/pages/user/followers?id=${this.userId}`
      });
    },
    
    // 导航到关注列表
    navigateToFollowing() {
      if (this.followingCount <= 0) {
        uni.showToast({
          title: '暂无关注',
          icon: 'none'
        });
        return;
      }
      
      uni.navigateTo({
        url: `/pages/user/following?id=${this.userId}`
      });
    },
    
    // 导航到编辑资料
    navigateToEditProfile() {
      uni.navigateTo({
        url: '/pages/my/profile-edit'
      });
    },
    
    // 导航到创作页面
    navigateToCreate() {
      uni.navigateTo({
        url: '/pages/create/create'
      });
    },
    
    // 处理错误
    handleError(message, error = null) {
      if (error) console.error(message, error);
      this.error = message;
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.profile-page {
  min-height: 100vh;
  background-color: #fff;
  
  .loading-container {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    z-index: 100;
    
    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 6rpx solid #f3f3f3;
      border-top: 6rpx solid #ff69b4;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }
    
    text {
      color: #666;
      font-size: 28rpx;
    }
  }
  
  .profile-scroll {
    height: 100vh;
    padding-bottom: 20rpx;
  }
  
  .user-header {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20rpx;
    background-color: #fff;
    
    .user-info {
      display: flex;
      align-items: flex-start;
      flex: 1;
      
      .avatar {
        width: 120rpx;
        height: 120rpx;
        border-radius: 60rpx;
        margin-right: 30rpx;
      }
      
      .info-content {
        flex: 1;
        
        .username {
          font-size: 36rpx;
          font-weight: bold;
          margin-bottom: 10rpx;
          color: #333;
        }
        
        .bio {
          font-size: 28rpx;
          color: #666;
          margin-bottom: 20rpx;
          line-height: 1.4;
        }
      }
    }
    
    .action-area {
      margin-left: 20rpx;
      
      .edit-profile-btn {
        padding: 12rpx 30rpx;
        background-color: #f5f5f5;
        border-radius: 30rpx;
        font-size: 26rpx;
        color: #333;
        text-align: center;
        border: 2rpx solid #e0e0e0;
      }
    }
  }
  
  .user-stats {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    background-color: #fff;
    
    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 0 20rpx;
      
      .count {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 6rpx;
      }
      
      .label {
        font-size: 26rpx;
        color: #666;
      }

      &:active {
        opacity: 0.7;
      }
    }
  }
  
  .works-section {
    padding: 30rpx;
    background-color: #fff;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 30rpx;
      color: #333;
      position: relative;
      padding-left: 20rpx;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 6rpx;
        height: 30rpx;
        width: 8rpx;
        background-color: #ff69b4;
        border-radius: 4rpx;
      }
    }
    
    .works-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20rpx;
      
      .work-item {
        aspect-ratio: 1;
        border-radius: 12rpx;
        overflow: hidden;
        position: relative;
        
        image {
          width: 100%;
          height: 100%;
          transition: transform 0.3s;
        }
        
        .work-info {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          padding: 16rpx;
          background: linear-gradient(to top, rgba(0,0,0,0.8), rgba(0,0,0,0));
          
          .work-title {
            color: #fff;
            font-size: 24rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            text-align: center;
          }
        }
        
        &:active {
          image {
            transform: scale(1.05);
          }
        }
      }
    }
    
    .empty-works {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60rpx 0;
      color: #999;
      
      .empty-image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 20rpx;
        opacity: 0.6;
      }
      
      .create-btn {
        margin-top: 30rpx;
        background-color: #ff69b4;
        color: white;
        font-size: 28rpx;
        padding: 12rpx 40rpx;
        border-radius: 30rpx;
      }
    }
    
    .loading, .no-more {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 30rpx 0;
      color: #999;
      font-size: 28rpx;
      
      .loading-spinner {
        width: 40rpx;
        height: 40rpx;
        border: 4rpx solid #f3f3f3;
        border-top: 4rpx solid #ff69b4;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 10rpx;
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
